package com.starhub.common.sys.user;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.starhub.engine.sys.user.bean.UserPermission;
import com.starhub.engine.sys.user.entity.SysUser;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 登录用户身份权限
 */
@NoArgsConstructor
public class LoginUser implements UserDetails {

    public SysUser user;

    public String userId;

    public LoginUser(String userId) {
        this.userId = userId;
    }
    public LoginUser(SysUser user, String userId, List<UserPermission> permissions) {
        this.userId = userId;
        this.user = user;
        this.permissions = permissions;
    }

    @JsonIgnore
    public List<UserPermission> permissions;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(permissions == null) return null;
        Collection<? extends GrantedAuthority> authorities= permissions.stream().map(item->new SimpleGrantedAuthority(item.getCode())).collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }


    public SysUser getUser() {
        return user;
    }

    public void setUser(SysUser user) {
        this.user = user;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
}


